package com.wakala.employment.fragment.finder;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.hjq.toast.Toaster;
import com.leaf.library.StatusBarUtil;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.FlowTagAdapter;
import com.wakala.employment.adapter.base.FlowTagSimpleAdapter;
import com.wakala.employment.adapter.jobCategory.CategoryConfigInfo;
import com.wakala.employment.adapter.jobCategory.JobCategoryAttrTreeVo;
import com.wakala.employment.adapter.jobCategory.JobCategoryTreeVo;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentJobCategoryAttrBinding;
import com.wakala.employment.http.TestApi;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.tip.ToastUtils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import co.lujun.androidtagview.TagContainerLayout;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link JobCategoryAttrFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class JobCategoryAttrFragment extends BaseFragment<FragmentJobCategoryAttrBinding> implements View.OnClickListener {

    private static  String TAG=JobCategoryAttrFragment.class.getSimpleName();

    Integer cid;

    List<JobCategoryAttrTreeVo>  categoryAttrList = new ArrayList<>();

    private ListView listView;

    private CommonAdapter<JobCategoryAttrTreeVo> listViewAdapter;

    private List<JobCategoryAttrTreeVo> selectedResultList = new ArrayList<>();
    /**
     * 选择的属性-》属性值 Map
     */
    private Map<Integer,List<JobCategoryAttrTreeVo>> selectedResultMap = new HashMap<>();

    @Nullable
    @Override
    protected View onCreateContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        cid = getArguments().getInt("cid");
        return super.onCreateContentView(inflater, container, attachToRoot);

    }

    @NonNull
    @Override
    protected FragmentJobCategoryAttrBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentJobCategoryAttrBinding.inflate(inflater, container, attachToRoot);
    }
    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("职业优势");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        binding.sbSave.setOnClickListener(this);
    }


    @Override
    protected void initViews() {
        //初始化listView
        listView = binding.listview;
        //创建适配器
        listViewAdapter = new CommonAdapter<JobCategoryAttrTreeVo>(getContext(),R.layout.item_job_category_attr_value,categoryAttrList) {

            @Override
            protected void convert(ViewHolder viewHolder, JobCategoryAttrTreeVo jobCategoryAttrVo, int i) {
                viewHolder.setText(R.id.tv_attr_name,jobCategoryAttrVo.getCategoryAttrName());
                FlowTagLayout mTagContainerLayout = (FlowTagLayout) viewHolder.getView(R.id.flowlayout_attr_value_select);
                mTagContainerLayout.setTag(jobCategoryAttrVo.getCategoryAttrId());//设置Tag为当前视图绑定的属性ID
                FlowTagSimpleAdapter tagAdapter = new FlowTagSimpleAdapter<JobCategoryAttrTreeVo>(getContext());
                mTagContainerLayout.setAdapter(tagAdapter);
                if(jobCategoryAttrVo.getMode()==0){
                    mTagContainerLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);//单选且不能需求
                    mTagContainerLayout.setSingleCancelable(true);//单选，是否可以取消  默认false不能，设置ture 可以取消选择也就是可以不选。
                }else if(jobCategoryAttrVo.getMode()==1){
                    mTagContainerLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);//单选且不能需求
                }else if(jobCategoryAttrVo.getMode()==2){
                    mTagContainerLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_MULTI);//可多选
                }

                //将当前工种属性的属性值设置为tag
                for(JobCategoryAttrTreeVo vo:jobCategoryAttrVo.getChildren()){
                    tagAdapter.addTag(vo);
                }

                mTagContainerLayout.setOnTagSelectListener((parent, position, selectedList) -> XToastUtils.toast(getSelectedText(parent, selectedList)));

            }
        };
        //listView绑定适配器
        listView.setAdapter(listViewAdapter);
        //
        getJobCategoryAttrTree(cid);
    }

    /**
     *
     * @param parent  当前操作的FlowTagLayout
     * @param selectedList 选择的所有tag
     * @return
     */
    private String getSelectedText(FlowTagLayout parent, List<Integer> selectedList) {
        StringBuilder sb = new StringBuilder("选中的内容：\n");
        List<JobCategoryAttrTreeVo> selectedAttrVoList = new ArrayList<>();
        Integer attrId = Integer.parseInt(parent.getTag().toString());
        selectedResultMap.remove(attrId);
        for (int index : selectedList) {
            JobCategoryAttrTreeVo attrTreeVo = (JobCategoryAttrTreeVo)parent.getAdapter().getItem(index);
            selectedAttrVoList.add(attrTreeVo);
            sb.append(parent.getAdapter().getItem(index));
            sb.append(";");
        }
        selectedResultMap.put(attrId,selectedAttrVoList);
        return sb.toString();
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id==R.id.sb_save){
            saveCategoryAttrValueResult();
        }
    }

    /**
     * 获取工种分类属性配置
     */
    @SuppressLint("CheckResult")
    private void getJobCategoryAttrTree(Integer categoryId){

        XHttpProxy.proxy(TestApi.IJobCategoryService.class)
                .listJobCategoryAttrTree(categoryId)
                .subscribeWith(new NoTipRequestSubscriber<List<JobCategoryAttrTreeVo>>() {

                    @Override
                    protected void onSuccess(List<JobCategoryAttrTreeVo> jobCategoryAttrVoList) {
                        Log.i(TAG,"-------------获取工种分类树------------------");
                        Toaster.show("数据加载成功");
                        categoryAttrList.clear();
                        categoryAttrList.addAll(jobCategoryAttrVoList);
                        XUtil.runOnUiThread(() -> {
                            listViewAdapter.notifyDataSetChanged();
                        });
                        Log.i(TAG,"-------------获取工种分类树------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);;
                        ToastUtils.toast(e.getDisplayMessage());
                        Log.i(TAG,"-------------获取工种分类树-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });
    }

    /**
     * 保存选择工种属性值
     */
    private void saveCategoryAttrValueResult(){
        Log.i(TAG, GsonUtils.toJson(selectedResultMap));
        //
    }
}